package com.siecom.hostservice;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.provider.Settings;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ivsign.android.IDCReader.IDCReadInterface;
import com.pos.api.Icc;
import com.pos.api.Mcr;
import com.pos.api.Pci;
import com.pos.api.Picc;
import com.pos.api.SM;
import com.pos.api.Sys;
import com.pos.emvcore.EmvCore;
import com.siecom.constconfig.ConstDefine;
import com.siecom.module.DeviceCallback;
import com.siecom.module.DeviceInterface;
import com.siecom.module.EmvCoreCallBackImpl;
import com.siecom.module.KeyBoardRunnable;
import com.siecom.nativelibs.NativeFunction;
import com.siecom.signaturepad.views.SignaturePad;
import com.siecom.tool.ByteTool;
import com.siecom.tool.ContextUtils;
import com.siecom.tool.LogUtil;
import com.siecom.tool.MoreClickListener;
import com.siecom.transport.ConnectStatusCallback;
import com.siecom.transport.SiecomDevice;
import com.siecom.transport.bluetooth.BLEperipheral;
import com.siecom.transport.bluetooth.BlueServer;
import com.siecom.transport.usbport.UsbServer;
import com.siecom.transport.usbport.receiver.OpenAccessoryReceiver;
import com.siecom.transport.usbport.receiver.UsbDetachedReceiver;
import com.siecom.zhq.hostservice.BuildConfig;
import com.siecom.zhq.hostservice.R;
import com.skyfishjy.library.RippleBackground;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


public class MainActivity extends Activity implements
        UsbDetachedReceiver.UsbDetachedListener ,
        OpenAccessoryReceiver.OpenAccessoryListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private UsbManager mUsbManager ;
    public static Context context;
    private static ImageView animeView;
    private static AlertDialog signaturePad = null;

    private int winScreenWidth = 0;
    private int winScreenHeight = 0;

    private RippleBackground rippleBackground;
    private static ImageView foundDevice;
    private ImageView centerBtn;


    private static TextView localNameView;
    private static TextView localAddressView;
    private static TextView remoteNameView;
    private static TextView remoteAddressView;
    private static TextView mTvVersion;
    private static TextView mTvShowDialog;

    private static final int idAnimeStart = 1;
    private static final int idAnimeStop = 2;
    private static final int SignaturePadStart = 3;
    private static final int SignaturePadStop = 4;
    private static final int insideCardStart = 5;
    private static final int insideCardStop = 6;
    private static final int swipeCardStart = 7;
    private static final int swipeCardStop = 8;
    private static final int nfcCardStart = 9;
    private static final int nfcCardStop = 10;
    private static final int inOneCardStart = 11;
    private static final int inOneCardStop = 12;
    private static final int fingerPrintStart = 13;
    private static final int fingerPrintStop = 14;
    private static final int keyBoardStart = 15;
    private static final int keyBoardStop = 16;
    private static final int keyBoardUpdate = 17;
    private static final int keyBoardLengthERR = 18;

    private static final int inputOne = 19;
    private static final int inputTwo = 20;
    private static final int inputThree = 21;
    private static final int inputfour = 22;
    private static final int inputfive = 23;
    private static final int showName = 24;
    private static final int disconnect = 25;
    public static final int animeStart = 26;
    public static final int updateAppProgress = 27;
    public static final int updateAppBegin = 28;

    private Button mClearButton;
    private static Button mSaveButton,mCancelButton;
    private static SignaturePad mSignaturePad;
    private static AlertDialog keyBoardDialog = null;
    private static EditText keyBoardText = null;
    private static String title;

    private static int passVoice = 0;
    private static TextView timeView,mTvTimeOut;

    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    private static CountDownTimer countDownTimer;

    private static int outTime;

    private static SoundPool soundPool;
    private static MediaPlayer mediaPlayer;

    private static HashMap<Integer, Integer> musicId = new HashMap<Integer, Integer>();

    private static volatile AnimationDrawable anim = null;

    public static int connectMode = ConstDefine.CONNECT_MODE_NONE; // -1 没有连接 0 蓝牙 1 BLE  2  USB


    public  static boolean isClean = true;
    int mWidth,mHeight;
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        LogUtil.setDebug(true); //日志开关
        LogUtil.setLog(true); // 本地日志开关
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (BuildConfig.FLAVOR.equals(ConstDefine.FLAVOR_GZNX)){
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }

        setContentView(R.layout.activity_main);

        context = this;

        winScreenWidth = ContextUtils.getScreenWidth(context);
        winScreenHeight = ContextUtils.getScreenHeight(context);
//        Log.e("winScreenWidth:" + winScreenWidth, "winScreenHeight:" + winScreenHeight);


        animeView = (ImageView) findViewById(R.id.anime);
        LayoutInflater inflater = LayoutInflater.from(this);

        rippleBackground = (RippleBackground) findViewById(R.id.content);
        rippleBackground.setBackgroundResource(R.mipmap.siecom); //代码设置不同的背景

        // rippleBackground.startRippleAnimation();

        foundDevice = (ImageView) findViewById(R.id.foundDevice);
        centerBtn = (ImageView) findViewById(R.id.centerImage);

        remoteNameView = (TextView) findViewById(R.id.remote_name);
        remoteAddressView = (TextView) findViewById(R.id.remote_address);

        localNameView = (TextView) findViewById(R.id.local_name);
        localAddressView = (TextView) findViewById(R.id.local_address);

        mTvVersion = findViewById(R.id.version_name);
        mTvVersion.setText("v " + DeviceInterface.getVersion() );


        setClickListener(); // 设置了多次点击事件

        mTvTimeOut = findViewById(R.id.timeView); //倒计时

        View layout = inflater.inflate(R.layout.signature_dialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(layout);
        builder.setCancelable(false);

        signaturePad = builder.create();
        mSignaturePad = (SignaturePad) layout.findViewById(R.id.signature_pad);

        timeView = (TextView) layout.findViewById(R.id.timeView);
        mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
            @Override
            public void onStartSigning() {

            }

            @Override
            public void onSigned() {
                mSaveButton.setEnabled(true);
                mClearButton.setEnabled(true);
                isClean = false;
            }

            @Override
            public void onClear() {
//                mSaveButton.setEnabled(false);
//                mClearButton.setEnabled(false);
                isClean = true;
            }
        });

        mClearButton = (Button) layout.findViewById(R.id.clear_button);
        mSaveButton = (Button) layout.findViewById(R.id.save_button);
        mCancelButton = layout.findViewById(R.id.btn_cancel_sign); //取消

        mClearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSignaturePad.clear();
                clearSignature();
            }
        });
//        mCancelButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                mSignaturePad.clear();
//                signaturePad.dismiss();
//            }
//        });

        centerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });


        loadSound();
        initDevice();//设置了蓝牙名称

        initEmvReadCard();

        DeviceInterface.initSignPad();
        IntentFilter mScreenOnFilter = new IntentFilter("android.intent.action.SCREEN_ON");
        this.registerReceiver(mScreenOReceiver, mScreenOnFilter);
        /* 注册机器锁屏时的广播 */
        IntentFilter mScreenOffFilter = new IntentFilter("android.intent.action.SCREEN_OFF");
        this.registerReceiver(mScreenOReceiver, mScreenOffFilter);

        //电池状态监听广播
        IntentFilter mBattaryFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        this.registerReceiver(mBatteryReceiver,mBattaryFilter);

        //初始化蓝牙
        this._bluetoothReceive = new BluetoothReciever();
        InitializeBluetoochAdapter();


        initUsbServer();



//        mETServer.listenFromPort();
//        test();

        //临时测试需要指纹模块上电
//        DeviceInterface.InitFinger();

//        mTvVersion.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                Toast.makeText(context,"请写入SN号",Toast.LENGTH_SHORT).show();
//                showTestDialog();
//                return false;
//            }
//        });

        //写入SN号界面
//        showTestDialog();
//        IDCReadInterface.DLL_IDOpen();

    }

    //    IosSerialServer mETServer = new IosSerialServer();
    @Override
    protected void onStart() {
//        mETServer.listenFromPort();
//        LogUtil.e(TAG,"in = " + mETServer.mInputStream  + "---- out =" + mETServer.mOutputStream);
        super.onStart();
        IDCReadInterface.DLL_IDOpen();
        //---------------------------------------------------------------------

//        if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
//            LogUtil.e(TAG,"BluetoothAdapter.getDefaultAdapter().isEnabled() = " + BluetoothAdapter.getDefaultAdapter().isEnabled());
//
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(enableBtIntent, 0);
//            finish();
//        }
        if(BluetoothAdapter.getDefaultAdapter().isEnabled()){
            Intent intent1 = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            intent1.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,3000);
            startActivityForResult(intent1,0);

            // 初始化BLE  区分版本
            if (BuildConfig.FLAVOR.equals(ConstDefine.FLAVOR_NETURAL)){
                BLEperipheral.getBleInstance(context).initBle(); //初始化BLE
//            IosSerialServer mETServer = new IosSerialServer();
//            mETServer.listenFromPort();
            }

        }

        // ---------------------------------------------------------------------
    }



    public void setClickListener(){
        localNameView.setOnClickListener(new MoreClickListener() {
            @Override
            public void onMoreClick(View view) {
                showPwdDialog();
            }
        });
    }

    public void showPwdDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.inputPWD);
        title = context.getResources().getString(R.string.inputPWD);
        keyBoardText = new EditText(context);
        keyBoardText.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);

        keyBoardText.setFocusable(true);
        keyBoardText.requestFocus();

        keyBoardDialog = builder.create();
        keyBoardDialog.setView(keyBoardText);

        keyBoardDialog.show();
        WindowManager.LayoutParams lp1 = keyBoardDialog.getWindow().getAttributes();
        lp1.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
        lp1.height = ContextUtils.getScreenHeight(context) - 100; //设置宽度
        lp1.dimAmount =0f;

        keyBoardDialog.getWindow().setAttributes(lp1);
        keyBoardDialog.setCancelable(false);
        CountDownTimer timer = new CountDownTimer(10*1000,1000) {
            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {
                keyBoardDialog.dismiss();

            }
        };
        timer.start();


        keyBoardText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                showAdjustVoiceLevel(timer,charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
                timer.cancel();
                timer.start();
            }
        });
    }

    public void showAdjustVoiceLevel(CountDownTimer timer,String charSequence){
        AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
        int level = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        if (charSequence.equals(ConstDefine.GZNX_PWD1) || charSequence.equals(ConstDefine.GZNX_PWD2)){
            timer.onFinish();
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("调节音量");

            SeekBar seekBar = new SeekBar(context);
            seekBar.setMax(15);
            seekBar.setProgress(level);
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                    am.setStreamVolume(AudioManager.STREAM_MUSIC,i,0);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    timer.start();
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    playVoice(ConstDefine.OPERATE_SUCC);

                }
            });
            keyBoardDialog = builder.create();
            keyBoardDialog.setView(seekBar);

            keyBoardDialog.show();
            WindowManager.LayoutParams lp1 = keyBoardDialog.getWindow().getAttributes();
            lp1.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
            lp1.height = ContextUtils.getScreenHeight(context) - 100; //设置宽度
            lp1.dimAmount =0f;

            keyBoardDialog.getWindow().setAttributes(lp1);
            keyBoardDialog.setCanceledOnTouchOutside(true);
            keyBoardDialog.setCancelable(true);

            keyBoardDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    timer.cancel();
                }
            });

        }
        //跳转到设置界面
        if(charSequence.equals(ConstDefine.ZG_SETTING)){
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            intent = new Intent();
            intent.setAction("HideNavigation_action");

            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
            intent.putExtra("cmd", "show");
            sendOrderedBroadcast(intent,null);


        }

    }


    public static void playSound(int speakerId) {

        mediaPlayer = MediaPlayer.create(context, speakerId);
        try {
            mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mediaPlayer.start();

    }

    public static void showKeyBoard() {

        animehandler.sendEmptyMessage(keyBoardStart);

    }

    public static void showKeyBoard(int passVoices,int timeOut) {
        outTime = timeOut;
        passVoice = passVoices;
        animehandler.sendEmptyMessage(keyBoardStart);

    }

    public static void showInputOne() {

        animehandler.sendEmptyMessage(inputOne);

    }

    public static void showInputTwo() {

        animehandler.sendEmptyMessage(inputTwo);

    }

    public static void showInputThree() {

        animehandler.sendEmptyMessage(inputThree);

    }

    public static void showInputFour() {

        animehandler.sendEmptyMessage(inputfour);

    }

    public static void showInputFive() {

        animehandler.sendEmptyMessage(inputfive);

    }

    public static void keyBoardLengthERR() {
        animehandler.sendEmptyMessage(keyBoardLengthERR);
    }

    public static void closeKeyBoard() {
        animehandler.sendEmptyMessage(keyBoardStop);
        MainActivity.getmSys().DLL_SysLedControl((byte) 0,(byte)0);
    }

    public static void closeKeyBoard(String msg) {

        animehandler.sendEmptyMessage(keyBoardStop);
        animehandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static void updateKeyBoard(int data) {
        Message message = new Message();
        message.what = keyBoardUpdate;
        Bundle bundle = new Bundle();
        bundle.putInt("data", data);
        message.setData(bundle);
        animehandler.sendMessage(message);
    }

    public static Bitmap getSignaturePadBitmap(boolean isTransparent) {
        //svg
        String svg = mSignaturePad.getSignatureSvg();
//        LogUtil.e(TAG,"svg == " + svg);
        if (isTransparent)
            return mSignaturePad.getTransparentSignatureBitmap();  //获取PNG格式 无法质量压缩
        else
            return mSignaturePad.getSignatureBitmap(); //获取白色背景图片 可以为JPG格式
    }

    public static void startFingerPrint(int timeOut) {
        outTime = timeOut;
        animehandler.sendEmptyMessage(fingerPrintStart);
    }

    public static void stopFingerPrint() {
        animehandler.sendEmptyMessage(fingerPrintStop);
    }

    public static void startInoneCard(int voiceType,int timeOut) {
        outTime = timeOut;
        Message msg = new Message();
        msg.what = inOneCardStart;
        msg.arg1 = voiceType;
        animehandler.sendMessage(msg);
    }

    public static void stopInoneCard() {
        animehandler.sendEmptyMessage(inOneCardStop);
    }

    public static void startNfcCard(int voiceType,int timeOut) {
        outTime = timeOut;
        Message msg = new Message();
        msg.what = nfcCardStart;
        msg.arg1 = voiceType;
        animehandler.sendMessage(msg);
    }

    public static void stopNfcCard() {
        animehandler.sendEmptyMessage(nfcCardStop);
    }

    public static void startSwipeCard(int timeOut) {
        outTime = timeOut;
        animehandler.sendEmptyMessage(swipeCardStart);
    }

    public static void stopSwipeCard() {
        animehandler.sendEmptyMessage(swipeCardStop);
    }

    public static void startInsideCard(int voiceType,int timeOut) {
        outTime = timeOut;
        Message msg = new Message();
        msg.what = insideCardStart;
        msg.arg1 = voiceType;
        animehandler.sendMessage(msg);
    }

    public static void stopInsideCard() {
        animehandler.sendEmptyMessage(insideCardStop);
    }

    public static void showSignaturePad(int time) {

        animehandler.sendEmptyMessage(SignaturePadStart);
        outTime = time;
        startSignature();

    }

    public static void startSignature() {
       DeviceInterface.startSignature();
    }

    public static void clearSignature() {
       DeviceInterface.clearSignature();
    }

    public static void disconnectBlue(){
        animehandler.sendEmptyMessage(disconnect);
    }


    public  interface SignatureCallball{

        public void endSign(int res,byte[] data);

    }
    public static void endSignature(SignatureCallball callball) {


        DeviceInterface.endSignature(new DeviceCallback() {
            @Override
            public void onStart() {
                LogUtil.e(TAG,"endSignature " + " onStart ");
            }

            @Override
            public void onError(Bundle bundle) {
                int res = bundle.getInt("code");
                LogUtil.e(TAG,"endSignature " + " onError res = " + res);
                callball.endSign(res,null);
            }

            @Override
            public void onSuccess(Bundle bundle) {
                LogUtil.e(TAG,"endSignature " + " onSuccess ");
                callball.endSign(0x90,bundle.getByteArray("data"));
            }

            @Override
            public void onCompleted(Bundle bundle) {
                try{
                    Thread.sleep(400);
                }catch (Exception e) {
                }
                LogUtil.e(TAG,"endSignature " + " onCompleted ");
                callball.endSign(10086,null);
            }
        },false);

    }

    public static void closeSignature() {
       DeviceInterface.closeSignature();
    }

    public static void cancelSignaturePad() {
        animehandler.sendEmptyMessage(SignaturePadStop);
    }

    public static void startIDAnime(int timeout) {
        outTime = timeout;
        animehandler.sendEmptyMessage(idAnimeStart);
    }

    public static void stopIDAnime() {
        animehandler.sendEmptyMessage(idAnimeStop);
    }

    public static void showUpdateAppProgress(Message msg){
        animehandler.sendMessage(msg);
    }
    public static Handler animehandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
//            Toast.makeText(context," ",Toast.LENGTH_SHORT).show();
            Runnable runnable;
            switch (msg.what) {
                case keyBoardLengthERR:
                    Toast.makeText(context, "密码长度错误", Toast.LENGTH_SHORT).show();
                    break;
                case keyBoardUpdate:
                    Bundle bundle = msg.getData();
                    int data = bundle.getInt("data");
                    LogUtil.e(TAG,"keyBoardUpdate data == " + data);
                    if (data  == 100){
                        MainActivity.playVoice(ConstDefine.VOICE_AGAIN_ENTER);
                        data = 0;
                    }
                    if (keyBoardDialog != null && keyBoardDialog.isShowing()) {
                        keyBoardDialog.setTitle(title + "已经输入长度" + data);
                        if (keyBoardText != null) {
                            StringBuffer buf = new StringBuffer();

                            for (int i = 0; i < data; i++)
                                buf.append("*");

                            keyBoardText.setText(buf.toString());
                        }
                    }
                    break;
                case keyBoardStop:
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardDialog.dismiss();
                        keyBoardText = null;
                        KeyBoardRunnable.unregisterPinEntryReceiver();//取消广播
                        LogUtil.e(TAG,"取消了广播-------------");
                    }
                    startCountDownFinish();
                    break;
                case keyBoardStart:

                    Toast.makeText(context,"请输入密码",Toast.LENGTH_SHORT).show();
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardDialog.dismiss();
                        keyBoardText = null;
                    }
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            if (passVoice == 0) {
                                MainActivity.playVoice(8);

                            } else if (passVoice == 1) {
                                MainActivity.playVoice(ConstDefine.VOICE_AGAIN_ENTER);//播放再次输入密码

                            } else if (passVoice == 2) {
                                MainActivity.playVoice(9);

                            } else if (passVoice == ConstDefine.VOICE_INPUT_Validate_code){
                                MainActivity.playVoice(ConstDefine.VOICE_INPUT_Validate_code);
                            } else if (passVoice == 81) {
                                MainActivity.playVoice(81);
                            }
                        }
                    };

                    executorService.submit(runnable);

                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle(R.string.inputPWD);
                    title = context.getResources().getString(R.string.inputPWD);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp1 = keyBoardDialog.getWindow().getAttributes();
                    lp1.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp1.height = ContextUtils.getScreenHeight(context) - 100; //设置宽度
                    lp1.dimAmount =0f;

                    keyBoardDialog.getWindow().setAttributes(lp1);
                    startCountDown();

                    break;

                case inputOne: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputOne);
                    title = context.getResources().getString(R.string.inputOne);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);

                    break;
                }
                case inputTwo: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputTwo);
                    title = context.getResources().getString(R.string.inputTwo);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);
                    break;
                }
                case inputThree: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputCop1);
                    title = context.getResources().getString(R.string.inputCop1);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);
                    break;
                }
                case inputfour: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputCop2);
                    title = context.getResources().getString(R.string.inputCop2);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);
                    break;
                }
                case inputfive: {
                    if (keyBoardDialog != null) {
                        keyBoardDialog.cancel();
                        keyBoardText = null;
                    }
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setTitle(R.string.inputQuery);
                    title = context.getResources().getString(R.string.inputQuery);
                    keyBoardText = new EditText(context);
                    keyBoardText.setInputType(InputType.TYPE_NULL);
                    keyBoardText.requestFocus();
                    keyBoardDialog = builder1.create();
                    keyBoardDialog.setView(keyBoardText);

                    keyBoardDialog.show();
                    WindowManager.LayoutParams lp2 = keyBoardDialog.getWindow().getAttributes();
                    lp2.width = ContextUtils.getScreenWidth(context) / 2; //设置宽度
                    lp2.height = ContextUtils.getScreenHeight(context) / 2; //设置宽度
                    keyBoardDialog.getWindow().setAttributes(lp2);
                    break;
                }
                case fingerPrintStart:
                    Toast.makeText(context,"读指纹",Toast.LENGTH_SHORT).show();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.playVoice(4);

                        }
                    };
                    executorService.submit(runnable);
                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.fingerprint_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    startCountDown();
                    break;
                case fingerPrintStop:
//                    Toast.makeText(context,"结束读指纹",Toast.LENGTH_SHORT).show();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
//                            soundPool.play(musicId.get(11), 1, 1, 0, 0, 1);
                        }
                    };
                    executorService.submit(runnable);
                    animeView.setBackgroundResource(R.drawable.fingerprint_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
//                    if(DeviceInterface.fingerImage != null)
//                    animeView.setImageBitmap(DeviceInterface.fingerImage);
                    startCountDownFinish();
                    break;
                case inOneCardStart:
                    int voiceType1 = msg.arg1;
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            if (voiceType1 == ConstDefine.VOICE_swipe_card_or_passbook)
                                MainActivity.playVoice(ConstDefine.VOICE_swipe_card_or_passbook);
                            else
                                MainActivity.playVoice(6);
                        }
                    };

                    executorService.submit(runnable);


                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.inone_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    startCountDown();
                    break;
                case inOneCardStop:
                    animeView.setBackgroundResource(R.drawable.inone_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    startCountDownFinish();
                    break;
                case nfcCardStart:
                    Toast.makeText(context,"请放置NFC卡",Toast.LENGTH_SHORT).show();
                    int type = msg.arg1;
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            if (type == ConstDefine.VOICE_swipe_card_or_passbook)
                                MainActivity.playVoice(ConstDefine.VOICE_swipe_card_or_passbook);
                            else
                                MainActivity.playVoice(3);
                        }
                    };

                    executorService.submit(runnable);

                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.nfc_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    startCountDown();
                    break;
                case nfcCardStop:
//                    Toast.makeText(context,"NFC",Toast.LENGTH_SHORT).show();
                    animeView.setBackgroundResource(R.drawable.nfc_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    startCountDownFinish();
                    break;
                case swipeCardStart:
                    Toast.makeText(context,"请刷卡",Toast.LENGTH_SHORT).show();

                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.playVoice(ConstDefine.VOICE_swipe_card_or_passbook);

                        }
                    };

                    executorService.submit(runnable);
                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.swipe_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    startCountDown();
                    break;
                case swipeCardStop:
                    animeView.setBackgroundResource(R.drawable.swipe_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    startCountDownFinish();
                    break;
                case insideCardStop:
                    animeView.setBackgroundResource(R.drawable.inside_card_anime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    startCountDownFinish();
                    break;
                case insideCardStart:
                    Toast.makeText(context,"请插卡",Toast.LENGTH_SHORT).show();
                    int voiceType = msg.arg1;
                    LogUtil.e(TAG,"voiceType == " + voiceType);
                    runnable = new Runnable() {
                        @Override
                        public void run() {

                            if (voiceType == ConstDefine.VOICE_swipe_card_or_passbook)
                                MainActivity.playVoice(ConstDefine.VOICE_swipe_card_or_passbook);
                            else
                                MainActivity.playVoice(2);
                        }
                    };

                    executorService.submit(runnable);
                    animeView.setVisibility(View.VISIBLE);
                    animeView.setBackgroundResource(R.drawable.inside_card_anime);

                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    startCountDown();
                    break;
                case idAnimeStart:
//                    Toast.makeText(context,"读身份证",Toast.LENGTH_SHORT).show();

                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.playVoice(1);
                        }
                    };

                    executorService.submit(runnable);
                    animeView.setBackgroundResource(R.drawable.idanime);
                    animeView.setVisibility(View.VISIBLE);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.start();
                    startCountDown();
                    break;

                case idAnimeStop:

                    animeView.setBackgroundResource(R.drawable.idanime);
                    anim = (AnimationDrawable) animeView.getBackground();
                    anim.stop();
                    animeView.setVisibility(View.INVISIBLE);
                    startCountDownFinish();
                    break;

                case SignaturePadStart:
                    Toast.makeText(context,"开始签名",Toast.LENGTH_SHORT).show();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.playVoice(7);
                        }
                    };

                    executorService.submit(runnable);
                    mSaveButton.setEnabled(true);
                    signaturePad.show();
                    WindowManager.LayoutParams lp = signaturePad.getWindow().getAttributes();
                    lp.width = ContextUtils.getScreenWidth(context); //设置宽度
                    lp.height = ContextUtils.getScreenHeight(context); //设置宽度
                    signaturePad.getWindow().setAttributes(lp);
                    startCountDown();

                    break;
                case SignaturePadStop:
                    startCountDownFinish();
                    if (signaturePad != null && signaturePad.isShowing())
                        signaturePad.cancel();
                    mSignaturePad.clear();
                    startCountDownFinish();
                    break;
                case showName:
                    Bundle bundle1 = msg.getData();
                    String name = bundle1.getString("data");
                    localNameView.setText(name);
                    LogUtil.e(TAG,"showName local=" + name);
                    localNameView.setVisibility(View.VISIBLE);
                    localAddressView.setText(BlueServer.getBTAddress());
                    localAddressView.setVisibility(View.VISIBLE);

                    break;
                case disconnect:
                    Toast.makeText(context, "外部连接设备已经断开连接，请重新连接", Toast.LENGTH_SHORT).show();

                    if (BuildConfig.FLAVOR.equals(ConstDefine.FLAVOR_SXNX)){
                        playVoice(ConstDefine.VOICE_DEVICE_DISCONNECT);
                    }
                    animeView.setVisibility(View.INVISIBLE);
                    remoteAddressView.setVisibility(View.INVISIBLE);
                    remoteNameView.setVisibility(View.INVISIBLE);
                    foundDevice.setVisibility(View.INVISIBLE);
                    // 0键盘  1指纹 2IC卡  3磁条卡  4蓝牙 5 身份证
                    MainActivity.getmSys().DLL_SysLedControl((byte) ConstDefine.LED_BLUETOOTH,(byte)0);
                    if (progressDialog != null && progressDialog.isShowing()) showUpdateProgress(-1);
                    break;
                case animeStart: {
                    Bundle bundle2 = msg.getData();
                    localNameView.setText(BlueServer.getName());
                    LogUtil.e(TAG,"animeStart =" + BlueServer.getName() );
                    localAddressView.setText(BlueServer.getBTAddress());
                    remoteNameView.setText(bundle2.getString("name"));
                    remoteAddressView.setText(bundle2.getString("address"));
                    localNameView.setVisibility(View.VISIBLE);
                    localAddressView.setVisibility(View.VISIBLE);
                    remoteNameView.setVisibility(View.VISIBLE);
                    remoteAddressView.setVisibility(View.VISIBLE);
                    Toast.makeText(context, "有外部设备连接", Toast.LENGTH_SHORT).show();
                    // 0键盘  1指纹 2IC卡  3磁条卡  4蓝牙 5 身份证
                    MainActivity.getmSys().DLL_SysLedControl((byte) ConstDefine.LED_BLUETOOTH,(byte)1);
                    if (BuildConfig.FLAVOR.equals(ConstDefine.FLAVOR_SXNX)){
                        playVoice(ConstDefine.VOICE_DEVICE_CONNECT);
                    }
                    break;
                }
                case updateAppBegin:
                    showUpdateDialog();
                    break;
                case updateAppProgress:
                    showUpdateProgress(msg.arg1);
                    break;

            }

        }

    };



    private static ProgressDialog progressDialog;

    public static void showUpdateDialog(){
        LogUtil.e(TAG,"开始升级-----------");
        if (progressDialog == null)
            progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);

        progressDialog.setTitle("升级中");
        progressDialog.setMax(100);
        progressDialog.setProgress(1);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();

    }


    public static void showUpdateProgress(int progress){
        progressDialog.setProgress(progress);
        switch (progress){
            case 100:
                progressDialog.dismiss();
                break;

            case -1:
                progressDialog.setTitle("升级失败，请重试");
                progressDialog.setCancelable(true);
                break;
        }

    }

      AlertDialog dialog = null;
    //测试页面
    public void showTestDialog(){

        View layout = LayoutInflater.from(context).inflate(R.layout.dialog_test, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(layout);
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
        WindowManager.LayoutParams lp = signaturePad.getWindow().getAttributes();
        lp.width = ContextUtils.getScreenWidth(context); //设置宽度
        lp.height = ContextUtils.getScreenHeight(context); //设置宽度
        dialog.getWindow().setAttributes(lp);

        ImageView ivFront = layout.findViewById(R.id.iv_front);
        ImageView ivBack = layout.findViewById(R.id.iv_back);
        Button buttonRead = layout.findViewById(R.id.button_read_id);
        Button btnClear = layout.findViewById(R.id.btn_clear);

        EditText editText = layout.findViewById(R.id.et_in_sn_code);
        buttonRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        DeviceInterface.setSerialCode(editText.getText().toString().trim());
//                    }
//                }).start();
                testCheckKey();
            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(null != dialog && dialog.isShowing()){
                    dialog.dismiss();
                    dialog = null;
                }
            }
        });

    }
    public void testCheckKey(){
        DeviceInterface.checkKeysExist(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {

            }

            @Override
            public void onSuccess(Bundle bundle) {

            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        },false);
    }

    public void test(){
//        byte[] bytes = ByteTool.hexStr2Bytes(ConstDefine.TEst_finger_data.replace(" ",""));
//        try {
//            LogUtil.e(TAG,"测试数据长度："+ bytes.length);
//            com.siecom.proto.Message.siecomproto msg = com.siecom.proto.Message.siecomproto.parseFrom(bytes);
//            LogUtil.e(TAG,"测试数据："+ msg.toString());
//        } catch (InvalidProtocolBufferException e) {
//            e.printStackTrace();
//        }
        String str = "02D1150000";
//        str = "02 D1 16 00 05 00 00 01 05 26";
        byte[] bytes = ByteTool.hexStr2Bytes(str.replace(" ",""));
        byte[] crcOut = new byte[2];
        NativeFunction.Crc16CCITT2(bytes,bytes.length  ,0,crcOut);
        LogUtil.e(TAG,"测试数据crcOut："+ ByteTool.byte2hex(crcOut));
    }

    public KeyBoardRunnable.PinEntryBroadcastReceiver mPinReceiver;


    private ExecutorService       mThreadPool;
    private OpenAccessoryReceiver mOpenAccessoryReceiver;
    private UsbDetachedReceiver mUsbDetachedReceiver;
    private static final String USB_ACTION               = "com.siecom.zhq.hostservice";
    private ParcelFileDescriptor mParcelFileDescriptor;
    private FileInputStream       mFileInputStream;
    private FileOutputStream      mFileOutputStream;
    private byte[]       mBytes        = new byte[1024];
    private StringBuffer mStringBuffer = new StringBuffer();
    PendingIntent pendingIntent = null;
    public void initUsbServer(){
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        mThreadPool = Executors.newFixedThreadPool(3);

        mUsbDetachedReceiver = new UsbDetachedReceiver(this);
        IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);

        registerReceiver(mUsbDetachedReceiver, filter);

        mOpenAccessoryReceiver = new OpenAccessoryReceiver(this);
         pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(USB_ACTION), 0);
        IntentFilter intentFilter = new IntentFilter(USB_ACTION);

        registerReceiver(mOpenAccessoryReceiver, intentFilter);



//        UsbAccessory usbAccessory[] = mUsbManager.getAccessoryList();
//        LogUtil.e(TAG ,"usbAccessoryList=" +usbAccessory);
//        if(null != usbAccessory && usbAccessory.length > 0){
//            for(int i=0; i<usbAccessory.length ;i++){
//                UsbAccessory accessory = usbAccessory[i];
//                LogUtil.e(TAG ,"getDescription=" + accessory.getDescription());
//                LogUtil.e(TAG ,"getManufacturer=" + accessory.getManufacturer());
//                LogUtil.e(TAG ,"getModel=" + accessory.getModel());
//                LogUtil.e(TAG ,"getSerial=" + accessory.getSerial());
//                LogUtil.e(TAG ,"getUri=" + accessory.getUri());
//                LogUtil.e(TAG ,"getVersion=" + accessory.getVersion());
//            }
//        }
    }


    public void initUsbServerConnect(){
        UsbAccessory[] accessories = mUsbManager.getAccessoryList();
        LogUtil.e(TAG ,"accessories==null? " +(accessories==null));
        UsbAccessory usbAccessory = (accessories == null ? null : accessories[0]);
//        Toast.makeText(MainActivity.context,"usbAccessory = null " + (usbAccessory==null) ,Toast.LENGTH_SHORT).show();
        if (usbAccessory != null) {
            LogUtil.e(TAG ,"usbAccessoryList=" +usbAccessory.toString());
//            if(!mUsbManager.hasPermission(usbAccessory)){
//                mUsbManager.requestPermission(usbAccessory, pendingIntent);
//            }
            Toast.makeText(MainActivity.context,"hasPermission " ,Toast.LENGTH_SHORT).show();
            if (mUsbManager.hasPermission(usbAccessory)) {
//                openAccessory(usbAccessory);
                LogUtil.e(TAG ,"已经拥有USB权限" );
                LogUtil.e(TAG ,"openAccessory" );
                SiecomDevice.startInitUsb(usbAccessory);
            } else {
                LogUtil.e(TAG ,"申请USB权限" );
                mUsbManager.requestPermission(usbAccessory, pendingIntent);
                LogUtil.e(TAG ,"申请USB权限 完成" );
            }
        }
    }
    /**
     * 打开Accessory模式
     *
     * @param usbAccessory
     */
    private void openAccessory(UsbAccessory usbAccessory) {
        mParcelFileDescriptor = mUsbManager.openAccessory(usbAccessory);
        LogUtil.e(TAG,"mParcelFileDescriptor=" + mParcelFileDescriptor);

        if (mParcelFileDescriptor != null) {
            FileDescriptor fileDescriptor = mParcelFileDescriptor.getFileDescriptor();
            mFileInputStream = new FileInputStream(fileDescriptor);
            mFileOutputStream = new FileOutputStream(fileDescriptor);
            LogUtil.e(TAG,"连接成功！！！");
            Toast.makeText(this,"连接成功！！！" ,Toast.LENGTH_SHORT).show();

            mThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    int i = 0;
                    while (i >= 0) {
                        try {
                            LogUtil.e(TAG,"i==" + i);
                            i = mFileInputStream.read(mBytes);
                        } catch (IOException e) {
                            e.printStackTrace();
                            break;
                        }
                        if (i > 0) {
                            mStringBuffer.append(new String(mBytes, 0, i) + "\n");
//                            mHandler.sendEmptyMessage(RECEIVER_MESSAGE_SUCCESS);
                            LogUtil.e(TAG,"接收成功！！！" + new String(mBytes, 0, i));
//                            Toast.makeText(MainActivity.this,"接收成功：" + mStringBuffer.toString() ,Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
        }
    }

    /**
     * USB 连接
     */
    @Override
    public void usbDetached() {
        SiecomDevice.closeUsb();
        LogUtil.e(TAG,"usbDetached-----");
        Toast.makeText(this,"usbDetached" ,Toast.LENGTH_SHORT).show();
    }
    @Override
    public void usbAttached() {
        LogUtil.e(TAG,"usb 已连接 -----");
        Toast.makeText(this,"usbAttached" ,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void openAccessoryModel(UsbAccessory usbAccessory) {
        LogUtil.e(TAG,"listener -- -- openAccessoryModel 打开了外设模式");
        Toast.makeText(this,"openAccessoryModel" ,Toast.LENGTH_SHORT).show();
        SiecomDevice.startInitUsb(usbAccessory);

    }

    @Override
    public void openAccessoryError() {
        LogUtil.e(TAG,"openDevicesError 打开失败");
        Toast.makeText(this,"openDevicesError" ,Toast.LENGTH_SHORT).show();
    }


    private static EmvCore mMainEmvCore = null;
    private static Icc mMainIcc = null;
    private static Picc mMainPicc = null;
    private static Pci mMainPci = null; //密钥
    private static SM mSm = null; //国密
    private static Mcr mMcr ;
    private static Sys mSys = null;
    public static int miTransCount = 0;

    private EmvCoreCallBackImpl mEmvCoreCallBackImpl = null;
    public void initEmvReadCard(){
        mMainIcc = new Icc(MainActivity.this, new Icc.IccConnectStatusListener()
        {
            @Override
            public void onConnectResult(boolean bRet) {
                // TODO Auto-generated method stub
                System.out.println("Icc bRet: " + bRet);
                LogUtil.e(TAG,"ICC Ret:" + bRet);
            }

        });

        mMainPicc = new Picc(MainActivity.this, new Picc.PiccConnectStatusListener()
        {

            @Override
            public void onConnectResult(boolean bRet) {
                // TODO Auto-generated method stub
                System.out.println("Picc bRet: " + bRet);
                LogUtil.e(TAG,"Picc初始化 Ret:" + bRet);
            }

        });

        mMainPci = new Pci(MainActivity.this, new Pci.PciConnectStatusListener() {

            @Override
            public void onConnectResult(boolean bRet) {
                // TODO Auto-generated method stub
                LogUtil.e(TAG,"Pci初始化：" + bRet);
            }
        });

        mMcr = new Mcr(this, new Mcr.McrConnectStatusListener(){
            @Override
            public void onConnectResult(boolean bRet) {
//                byte[] bytes = new byte[50];
//                mMcr.DLL_McrReadVersion(bytes);
//                LogUtil.e(TAG,"Mcr初始化：" + bRet + "    version == " + new String(bytes).trim());

            }
        });
        //国密初始化
        mSm = new SM(context, new SM.SMConnectStatusListener() {
            @Override
            public void onConnectResult(boolean b) {
                LogUtil.e(TAG,"SM初始化：" + b);
            }
        });

        mSys = new Sys(context, new Sys.SysConnectStatusListener() {
            @Override
            public void onConnectResult(boolean bRet) {
//                byte[] bytes = new byte[50];
//                int ret = mSys.DLL_SysGetDLLVersion(bytes);
//
//                if (ret == 0){
//                    String inOneVerson = bytes[0] + "." + bytes[1] + "." +bytes[2];
//                    LogUtil.e(TAG,"mSys：" + bRet + "    inOneVerson == " + inOneVerson);
//                }
            }
        });

        mEmvCoreCallBackImpl = new EmvCoreCallBackImpl(mMainIcc, mMainPicc, mMainPci);

        mMainEmvCore = new EmvCore();
        int iRet = -1;
        File fileDir = MainActivity.this.getFilesDir();

        String strPath = fileDir.getPath();
        strPath += "/EmvCore";
        iRet = mMainEmvCore.EmvLibInit(mEmvCoreCallBackImpl, strPath.getBytes(), strPath.getBytes().length);

        System.out.println("EmvLibInit iRet: " + iRet);
    }

    public void uninit(){
        mMainIcc.DLL_IccRelease();
        mMainPci.DLL_PciRelease();
        mMainPicc.DLL_PiccRelease();
        mSys.DLL_SysRelease();
        mSm.DLL_SMRelease();
        mMcr.DLL_McrRelease();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        mWidth = mSignaturePad.getWidth();
        mHeight = mSignaturePad.getHeight();
//        LogUtil.e("GJ","onWindowFocusChanged: width = " + mWidth + "   height = " + mHeight);
    }


    private void loadSound() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (soundPool != null) {
                    soundPool.release();
                    soundPool = null;
                }
                soundPool = new SoundPool.Builder().setMaxStreams(15).build();

                musicId.put(1, soundPool.load(context, R.raw.idcard, 1));
                musicId.put(2, soundPool.load(context, R.raw.inside_card, 1));
                musicId.put(3, soundPool.load(context, R.raw.put_card, 1));
                musicId.put(4, soundPool.load(context, R.raw.pls_put_finger, 1));
                musicId.put(401, soundPool.load(context, R.raw.pls_put_finger, 1));
                musicId.put(402, soundPool.load(context, R.raw.pls_put_finger, 1));
                musicId.put(5, soundPool.load(context, R.raw.swipe_card, 1));
                musicId.put(6, soundPool.load(context, R.raw.swipe_or_inside, 1));
                musicId.put(7, soundPool.load(context, R.raw.pls_confirm_and_sign, 1));
                musicId.put(8, soundPool.load(context, R.raw.press_pwd, 1));
                musicId.put(9, soundPool.load(context, R.raw.errorpass, 1));
                musicId.put(ConstDefine.VOICE_AGAIN_ENTER, soundPool.load(context, R.raw.againenter, 1)); //再次输入密码
                musicId.put(ConstDefine.VOICE_OUT_FINGER, soundPool.load(context, R.raw.out_finger, 1));

                musicId.put(ConstDefine.OPERATE_SUCC, soundPool.load(context, R.raw.operate_success, 1));//
                musicId.put(ConstDefine.OPERATE_FAIL, soundPool.load(context, R.raw.operate_fail_pls_try_again, 1));

                musicId.put(ConstDefine.VOICE_INPUT_Validate_code, soundPool.load(context, R.raw.pls_input_validate_code, 1));
                musicId.put(ConstDefine.VOICE_swipe_card_or_passbook, soundPool.load(context, R.raw.pls_swipe_card_or_pass_book, 1));
                musicId.put(ConstDefine.VOICE_PWD_TOO_SIMPLE, soundPool.load(context, R.raw.pwd_too_simple_pls_input_again, 1));


                musicId.put(ConstDefine.VOICE_DEVICE_CONNECT,soundPool.load(context,R.raw.device_connected,1));
                musicId.put(ConstDefine.VOICE_DEVICE_DISCONNECT,soundPool.load(context,R.raw.device_disconnected,1));
            }
        };
        executorService.submit(runnable);

    }

    public static void playVoice(int id){

        soundPool.autoPause();
        soundPool.play(musicId.get(id),1,1,0,0,1);
    }
    /**  用户进行调用
     *        0：请输入密码
     *      * 1：请再次输入密码
     *      * 2：密码错误，请重新输入密码
     *      * 3：请放置身份证
     *      * 4：请放置IC卡
     *      * 5：请插入IC卡
     *      * 6：请刷磁条卡
     *      * 7：请签字
     *      * 8：请录入指纹
     *      * 9：请重新录入指纹
     *      * a：操作成功
     * @param voiceType
     */
    public static void soundPoolPlayByUser(int voiceType){
        if(voiceType >= 0 && voiceType < musicId.size()){
            soundPool.autoPause();
            if (voiceType == 0) //请输入密码
                soundPool.play(8,1,1,0,0,1);
            if (voiceType == 1) //请再次输入密码
                soundPool.play(10,1,1,0,0,1);
            if (voiceType == 2) //密码错误，请重新输入密码
                soundPool.play(9,1,1,0,0,1);
            if (voiceType == 3) //请请放置身份证
                soundPool.play(1,1,1,0,0,1);
            if (voiceType == 4) //请放置IC卡
                soundPool.play(3,1,1,0,0,1);
            if (voiceType == 5) //请插入IC卡
                soundPool.play(2,1,1,0,0,1);
            if (voiceType == 6) //请刷磁条卡
                soundPool.play(5,1,1,0,0,1);
            if (voiceType == 7) //请签字
                soundPool.play(7,1,1,0,0,1);
            if (voiceType == 8) //请录入指纹
                soundPool.play(4,1,1,0,0,1);
            if (voiceType == 9) //请重新录入指纹
                soundPool.play(4,1,1,0,0,1);
            if (voiceType == 10) //操作成功
                soundPool.play(12,1,1,0,0,1);
        }
    }

    // 用广播接收器来更新蓝牙扫描的状态
    private class BluetoothReciever extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

//            LogUtil.e("=========================","蓝牙状态是："+action);
            switch (action){
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_TURNING_ON:
                            Log.e(TAG, "TURNING_ON--");
                            break;
                        case BluetoothAdapter.STATE_ON:

                            Log.e(TAG, "STATE_ON--");
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            Log.e(TAG, "STATE_TURNING_OFF--");
                            disconnectBlue();
                            finish();
                            break;
                        case BluetoothAdapter.STATE_OFF:

                            Log.e(TAG, "STATE_OFF--");
                            break;
                    }
                    break;
                case "android.bluetooth.BluetoothAdapter.STATE_ON":
                    LogUtil.e(TAG,"STATE_ON---- ");
                    break;

                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                    LogUtil.e(TAG,"ACTION_BOND_STATE_CHANGED---- ");
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    LogUtil.e(TAG,"ACTION_DISCOVERY_FINISHED---- ");

                    break;
                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    LogUtil.e(TAG,"ACTION_ACL_CONNECTED---- ");
                    connectMode = ConstDefine.CONNECT_MODE_BLUE;
                    break;

                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    LogUtil.e(TAG,"ACTION_ACL_DISCONNECTED---- ");
                    disconnectBlue();
                    break;
            }

        }
    }

    private BluetoothReciever _bluetoothReceive = null;
    private void InitializeBluetoochAdapter() {

        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction("android.bluetooth.device.action.FOUND");
        localIntentFilter
                .addAction("android.bluetooth.device.action.BOND_STATE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.SCAN_MODE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.STATE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.device.action.PAIRING_REQUEST");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.DISCOVERY_STARTED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        localIntentFilter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
        localIntentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
        localIntentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");

        this.registerReceiver(this._bluetoothReceive, localIntentFilter);

    }

    public static JSONObject mBattaryInfoJB = new JSONObject();
    private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder sb = new StringBuilder();
            int rawlevel = intent.getIntExtra("level", -1);
            int scale = intent.getIntExtra("scale", -1);
            int status = intent.getIntExtra("status", -1);
            int health = intent.getIntExtra("health", -1);
            int level = -1;
            if(rawlevel >= 0 && scale > 0){
                level = (rawlevel*100)/scale;
            }
            sb.append("电池电量: ");
            sb.append(level + "%\n");

            String healthStatus = "";
            switch (health) {
                case BatteryManager.BATTERY_HEALTH_UNKNOWN:
                    healthStatus = "UNKNOWN";
                    break;
                case BatteryManager.BATTERY_HEALTH_GOOD:
                    healthStatus = "GOOD";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                    healthStatus = "OVERHEAT";
                    break;
                case BatteryManager.BATTERY_HEALTH_DEAD:
                    healthStatus = "DEAD";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                    healthStatus = "OVER VOLTAGE";
                    break;
                case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
                    healthStatus = "UNSPECIFIED FAILURE";
                    break;
                case BatteryManager.BATTERY_HEALTH_COLD:
                    healthStatus = "COLD";
                    break;

            }
            sb.append("健康度:" + healthStatus + "\n");
            int direction = -1;
            int isBatteryExist = 1;
            String batteryStatus ="";
            switch (status) {
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    batteryStatus="[没有安装电池]";
                    isBatteryExist = 0;
                    break;
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    batteryStatus="[正在充电]";
                    direction = 1;
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    batteryStatus="[已经充满]";
                    direction = 2;
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    batteryStatus="[放电中]";
                    direction = 0;
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    batteryStatus="[未充电]";
                    break;
                default:
                    if(level <= 10)
                        sb.append("[电量过低，请充电]");
                    else if (level <= 100) {
                        sb.append("[未连接充电器]");
                    }
                    break;
            }
            sb.append(batteryStatus);
            LogUtil.d(TAG,"电池状态:" + sb.toString());
            try {
                mBattaryInfoJB.put("direction",direction); //充放电方向
                mBattaryInfoJB.put("isBatteryExist",isBatteryExist); //是否有电池
                mBattaryInfoJB.put("electricity",level+"%"); //电量百分比
                mBattaryInfoJB.put("code",0); //成功
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };
    public static boolean mScreenOn = true;
    public static boolean isWakeUp = false;
    private BroadcastReceiver mScreenOReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals("android.intent.action.SCREEN_ON")) {
                mScreenOn = true;
                Log.e(TAG, "action == SCREEN_ON");

//                Intent intent2 = new Intent(getApplicationContext(), MainActivity.class);
//                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                PendingIntent restartIntent = PendingIntent.getActivity(
//                        getApplicationContext(), 0, intent2, 0);
//
//                AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent);
//
//                // 关闭当前应用
//                HKBaseApplication.finishAllActivity();
//                HKBaseApplication.finishProgram();
//                System.gc();
//
////                loadSound();
////                Distribution.screeSwitch(true);
////                initDevice();


            } else if (action.equals("android.intent.action.SCREEN_OFF")) {
                mScreenOn = false;
                Log.e("action", "SCREEN_OFF");
//                if (keyBoardDialog != null) {
//                    keyBoardDialog.cancel();
//                    keyBoardText = null;
//                }
//                DeviceInterface.lightOff();
//                Distribution.screeSwitch(false);
////                DeviceInterface.allClose();
//                SiecomDevice.closeBT();
//                SiecomDevice.closeSerial();
//                closeSignature();
//                localNameView.setVisibility(View.INVISIBLE);
//                localAddressView.setVisibility(View.INVISIBLE);
//                remoteAddressView.setVisibility(View.INVISIBLE);
//                remoteNameView.setVisibility(View.INVISIBLE);
            }else if(action.equals("com.pos.pinentry")){
                LogUtil.e(TAG,"PinLen:"+intent.getIntExtra("pinLen", 0));
            }
        }

    };

    public static void startCountDown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
            timeView.setText("");
            mTvTimeOut.setText("");
        }
        countDownTimer = new CountDownTimer(outTime, 1000) {

            @Override

            public void onTick(long millisUntilFinished) {

                // 倒计时中的方法
                timeView.setText(millisUntilFinished / 1000 + "秒");
                mTvTimeOut.setText(millisUntilFinished / 1000 + "秒");
            }

            @Override

            public void onFinish() {

                // 倒计时结束后的方法

                timeView.setText("");
                mTvTimeOut.setText("");
            }

        };

        countDownTimer.start();

    }


    public static void startCountDownFinish(){
        if (countDownTimer != null)
            countDownTimer.cancel();

        mTvTimeOut.setText("");
    }

    @Override
    protected void onResume() {
        LogUtil.e(TAG,"onResume==");
        super.onResume();
        if (UsbServer.mUSbConnectState != 0){
            initUsbServerConnect(); //激活USB
        }

        //隐藏导航栏
        if (BuildConfig.FLAVOR.equals(ConstDefine.FLAVOR_GZNX)){
            Intent intent = new Intent();
            intent.setAction("HideNavigation_action");

            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
            intent.putExtra("cmd", "hide"); // show 显示
            sendOrderedBroadcast(intent,null);
        }


    }

    @Override
    public void onStop() {
        super.onStop();
        MainActivity.getmMainPicc().DLL_PiccClose(); // onStop 后关闭
        Log.e("onStop", "onStop===");
//        IDCReadInterface.DLL_IDClose(); //关闭身份证
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("onDestroy", "onDestroy");
//        DeviceInterface.allClose();
        closeSignature();
        unregisterReceiver(mScreenOReceiver);
        unregisterReceiver(mOpenAccessoryReceiver);
        unregisterReceiver(mUsbDetachedReceiver);
        unregisterReceiver(_bluetoothReceive);
        unregisterReceiver(mBatteryReceiver);
        if (mParcelFileDescriptor != null) {
            try {
                mParcelFileDescriptor.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mFileInputStream != null) {
            try {
                mFileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mFileOutputStream != null) {
            try {
                mFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        uninit();
        // 0键盘  1指纹 2IC卡  3磁条卡  4蓝牙 5 身份证
        MainActivity.getmSys().DLL_SysLedControl((byte) 4,(byte)0);
//        SiecomDevice.closeBT(); //关闭蓝牙
        SiecomDevice.closeUsb(); //关闭USB
        finish();
    }

    public static void setSignatureCancleListener(View.OnClickListener listener){
        mCancelButton.setOnClickListener(listener);
    }
    public static void setSignatureListener(View.OnClickListener listener) {

        mSaveButton.setOnClickListener(listener);

    }

    public static void showBlueName(String deviceName) {
        Message message = new Message();
        message.what = showName;
        Bundle bundle = new Bundle();
        bundle.putString("data", deviceName);
        message.setData(bundle);
        animehandler.sendMessage(message);

    }

    public static Observer<BluetoothSocket> observer = null;
    public void startServer() {
        connectMode = 0; //安卓普通U蓝牙模式
//        LogUtil.e(TAG,"observer==null " + (observer==null));
        if(observer == null){
            observer = new Observer<BluetoothSocket>() {

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "蓝牙打开失败正在重试:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    //  CrashHandler.saveCrashInfo2File(e);
                    // DeviceInterface.allClose();
                }

                @Override
                public void onComplete() {

                    Log.e("accept", "Completed");

                }

                @Override
                public void onSubscribe(@NonNull Disposable disposable) {

                }

                @Override
                public void onNext(BluetoothSocket socket) {
                    LogUtil.e(TAG,"onNext onNext onNext");
                    /**
                     * 监听通讯状态
                     */
                    SiecomDevice.startListen(new ConnectStatusCallback() {
                        @Override
                        public void onConnectStart() {
                            Log.e("ConnectStatusCallback", "onConnectStart");
                        }

                        @Override
                        public void onConnected() {
                            connectMode = 0;
                            Log.e("ConnectStatusCallback", "onConnected");
                            // 0键盘  1指纹 2IC卡  3磁条卡  4蓝牙 5 身份证
                            MainActivity.getmSys().DLL_SysLedControl((byte) 4,(byte)1);
                        }

                        @Override
                        public void onDisConnect(Throwable e) {
                            // DeviceInterface.allClose();
                            Log.e("ConnectStatusCallback", e.getMessage());
                            animehandler.sendEmptyMessage(disconnect);

                            // 0键盘  1指纹 2IC卡  3磁条卡  4蓝牙 5 身份证
                            MainActivity.getmSys().DLL_SysLedControl((byte) 4,(byte)0);
                        }
                    });

                    foundDevice();

                    rippleBackground.stopRippleAnimation();

                    playAnimator();
                    Message message = new Message();
                    message.what = animeStart;
                    Bundle bundle = new Bundle();
                    bundle.putString("name", socket.getRemoteDevice().getName());
                    bundle.putString("address", socket.getRemoteDevice().getAddress());
                    LogUtil.e(TAG,"name == " + socket.getRemoteDevice().getName() + " ---- " + socket.getRemoteDevice().getAddress());
                    message.setData(bundle);
                    animehandler.sendMessageDelayed(message, 1000);


                }
            };
        }

        SiecomDevice.initServer(observer, AndroidSchedulers.mainThread());


    }

    public void initDevice() {
        startServer();

    }


    private void foundDevice() {
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(400);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        ArrayList<Animator> animatorList = new ArrayList<Animator>();
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(foundDevice, "ScaleX", 0f, 1.2f, 1f);
        animatorList.add(scaleXAnimator);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(foundDevice, "ScaleY", 0f, 1.2f, 1f);
        animatorList.add(scaleYAnimator);
        animatorSet.playTogether(animatorList);
        foundDevice.setVisibility(View.VISIBLE);
        animatorSet.start();
    }

    private void playAnimator() {
        float cx = centerBtn.getX();
        float cy = centerBtn.getY();
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(centerBtn,
                "x", cx, 0f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(centerBtn,
                "y", cy, 0f);
        AnimatorSet animSet = new AnimatorSet();

        float x1 = foundDevice.getWidth();
        float y1 = foundDevice.getHeight();

        ObjectAnimator anim3 = ObjectAnimator.ofFloat(foundDevice,
                "x", foundDevice.getX(), winScreenWidth - x1);
        ObjectAnimator anim4 = ObjectAnimator.ofFloat(foundDevice,
                "y", foundDevice.getY(), winScreenHeight - y1);

        animSet.play(anim1).with(anim3);
        animSet.play(anim2).with(anim4);
        animSet.setDuration(1000);
        animSet.start();
    }



    public File getAlbumStorageDir(String albumName) {
        // Get the directory for the user's public pictures directory.
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), albumName);
        if (!file.mkdirs()) {
            Log.e("SignaturePad", "Directory not created");
        }
        return file;
    }

    public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
    }


    private void scanMediaFile(File photo) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(photo);
        mediaScanIntent.setData(contentUri);
        MainActivity.this.sendBroadcast(mediaScanIntent);
    }

    public boolean addSvgSignatureToGallery(String signatureSvg) {
        boolean result = false;
        try {
            File svgFile = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.svg", System.currentTimeMillis()));
            OutputStream stream = new FileOutputStream(svgFile);
            OutputStreamWriter writer = new OutputStreamWriter(stream);
            writer.write(signatureSvg);
            writer.close();
            stream.flush();
            stream.close();
            scanMediaFile(svgFile);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean addJpgSignatureToGallery(Bitmap signature) {
        boolean result = false;
        try {
            File photo = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.jpg", System.currentTimeMillis()));
            saveBitmapToJPG(signature, photo);
            scanMediaFile(photo);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Icc getmMainIcc(){
        return mMainIcc;
    }
    public static Picc getmMainPicc(){
        return mMainPicc;
    }
    public static Pci getmMainPci(){ return mMainPci; }
    public static Mcr getMainMcr(){
        return mMcr;
    }
    public static EmvCore getEmvCore()
    {
        return mMainEmvCore;
    }
    public static SM getmSm(){ return mSm;}
    public static Sys getmSys(){return mSys;}





}
